package me.xue.communityhealth.admin.controller;

import me.xue.communityhealth.model.Disease;
import me.xue.communityhealth.service.DiseaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.List;

@Controller
public class DiseasesController {

    private final DiseaseService diseaseService;

    @Autowired
    public DiseasesController(DiseaseService diseaseService) {
        this.diseaseService = diseaseService;
    }

    @GetMapping("/diseases")
    public String allDisease(@ModelAttribute("message") String message, Model model) {
        List<Disease> diseases = diseaseService.findAll();
        model.addAttribute("diseases", diseases);
        return "diseases";
    }

    @GetMapping("/disease/add")
    public String addDiseasePage(Model model) {
        model.addAttribute("disease", new Disease());
        return "disease_edit";
    }

    @PostMapping("/disease")
    public String addDisease(@Valid Disease disease, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            return "disease_edit";
        }
        int saved = diseaseService.save(disease);
        if (saved == 1) {
            redirectAttributes.addFlashAttribute("message", "添加成功");
            return "redirect:/diseases";
        }
        return "disease_edit";
    }

    @GetMapping("/disease/{id:\\d+}/edit")
    public String updateDiseasePage(@PathVariable("id") Integer id, Model model) {
        model.addAttribute("disease", diseaseService.findOne(id));
        return "disease_edit";
    }

    @PutMapping("/disease")
    public String updateDisease(@Valid Disease disease, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            return "disease_edit";
        }
        int updated = diseaseService.update(disease);
        if (updated == 1) {
            redirectAttributes.addFlashAttribute("message", "修改成功");
            return "redirect:/diseases";
        }
        return "disease_edit";
    }

    @DeleteMapping("/disease/{id:\\d+}")
    @ResponseBody
    public String deleteDisease(@PathVariable("id") Integer id) {
        int deleted = diseaseService.delete(id);
        if (deleted == 1) {
            return "success";
        }
        return "fail";
    }

}
